package com.open4cn.simulator.protocol.huagao;

import cn.hutool.core.util.HexUtil;
import com.open4cn.simulator.core.ext.HuaGaoOutMessage;
import com.open4cn.simulator.core.util.StrFillUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author yinxiaopeng
 * @version 1.0.0
 * @company 致景科技
 * @department 飞梭BU/研发
 * @description 华高协议加密
 * @Email yinxiaopeng@zj.tech
 * @date 2022-05-02 01:56
 */
public class HuaGaoEncoder extends MessageToByteEncoder<HuaGaoOutMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, HuaGaoOutMessage msg, ByteBuf out) throws Exception {
        String hexStr = msg.get();
        int len = hexStr.length() / 2;
        String lenHexStr = Integer.toHexString(len);
        lenHexStr = StrFillUtil.fillLeft(lenHexStr, 2, "0");
        lenHexStr = StrFillUtil.fillRight(lenHexStr, 8, "0");
        StringBuilder builder = new StringBuilder();
        builder.append(lenHexStr);
        builder.append(hexStr);
        out.writeBytes(HexUtil.decodeHex(builder.toString()));
    }
}
